<template>
    <div class="page">
        <h2 class="title">货主合同审批</h2>

        <div class="search">
            <div class="row">
                <label>合同标题：</label>
                <input v-model="q.contractTitle" placeholder="请输入合同标题" />
                <label>货主单位：</label>
                <input v-model="q.unitName" placeholder="请输入货主单位" />
                <label>货主负责人：</label>
                <input v-model="q.ownerName" placeholder="请输入货主负责人" />
            </div>
            <div class="row">
                <label>经办人：</label>
                <input v-model="q.handler" placeholder="请输入经办人" />
                <label>签订时间：</label>
                <input type="date" v-model="q.signingStart" />
                <span> - </span>
                <input type="date" v-model="q.signingEnd" />
                <label>状态：</label>
                <select v-model="q.status">
                    <option value="">全部</option>
                    <option value="0">待审批</option>
                    <option value="2">已通过</option>
                    <option value="3">已拒绝</option>
                </select>
                <button class="btn primary" @click="search">查询</button>
                <button class="btn" @click="reset">重置</button>
            </div>
        </div>

        <div class="tabs">
            <button :class="['tab', { active: tab === 'all' }]" @click="tab = 'all'">全部</button>
            <button :class="['tab', { active: tab === 'pending' }]" @click="tab = 'pending'">待审批</button>
            <button :class="['tab', { active: tab === 'approved' }]" @click="tab = 'approved'">已审批</button>
        </div>

        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>合同编号</th>
                        <th>合同标题</th>
                        <th>货主单位</th>
                        <th>货主负责人</th>
                        <th>线路</th>
                        <th>吨运价</th>
                        <th>包车条件吨位</th>
                        <th>包车金额</th>
                        <th>签订日期</th>
                        <th>经办人</th>
                        <th>创建时间</th>
                        <th>状态</th>
                        <th>审批人</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td :colspan="14" style="text-align:center">加载中...</td>
                    </tr>
                    <tr v-else-if="displayRows.length === 0">
                        <td :colspan="14" style="text-align:center">暂无数据</td>
                    </tr>
                    <tr v-for="r in displayRows" :key="r.id">
                        <td>{{ r.contractNumber }}</td>
                        <td>{{ r.contractTitle }}</td>
                        <td>{{ r.unitName }}</td>
                        <td>{{ r.ownerName }}</td>
                        <td>{{ r.routeName }}</td>
                        <td>{{ r.tonFreightRate }}</td>
                        <td>{{ r.charterConditionTonnage }}</td>
                        <td>{{ r.charterAmount }}</td>
                        <td>{{ r.signingDate }}</td>
                        <td>{{ r.handler }}</td>
                        <td>{{ r.createdAt }}</td>
                        <td>{{ r.status }}</td>
                        <td>{{ r.approver || '-' }}</td>
                        <td>
                            <a href="javascript:void(0)" @click="view(r)">查看</a>
                            &nbsp;|&nbsp;
                            <a href="javascript:void(0)" @click="approve(r)">通过</a>
                            &nbsp;|&nbsp;
                            <a href="javascript:void(0)" @click="reject(r)">拒绝</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="pagination" v-if="total > 0">
            <span class="sum">共{{ totalPage }}页/{{ total }}条数据</span>
            <button class="nav" :disabled="page === 1" @click="goto(page - 1)">‹</button>
            <button v-for="p in pagesToShow" :key="p" :class="{ num: true, active: p === page }" @click="goto(p)">{{ p
                }}</button>
            <button class="nav" :disabled="page >= totalPage" @click="goto(page + 1)">›</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'

const router = useRouter()
const counts = useCounterStore()

const q = reactive({ contractTitle: '', unitName: '', ownerName: '', handler: '', signingStart: '', signingEnd: '', status: '' })
const tab = ref<'all' | 'pending' | 'approved'>('all')
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPage = ref(0)
const rows = ref<any[]>([])
const loading = ref(false)

const pagesToShow = computed(() => {
    const max = Math.max(totalPage.value, 1)
    const cur = Math.min(Math.max(page.value, 1), max)
    const arr: number[] = []
    const start = Math.max(1, cur - 2)
    const end = Math.min(max, cur + 2)
    for (let i = start; i <= end; i++) arr.push(i)
    return arr
})

const displayRows = computed(() => {
    if (tab.value === 'all') return rows.value
    if (tab.value === 'pending') return rows.value.filter(r => String(r.status) === '0' || String(r.status) === '待审批')
    return rows.value.filter(r => String(r.status) === '2' || String(r.status) === '已通过' || String(r.status) === '已拒绝')
})

async function fetchList() {
    loading.value = true
    try {
        const params = new URLSearchParams()
        params.append('PageIndex', String(page.value))
        params.append('PageSize', String(pageSize.value))
        if (q.contractTitle) params.append('ContractTitle', q.contractTitle)
        if (q.unitName) params.append('UnitName', q.unitName)
        if (q.ownerName) params.append('OwnerName', q.ownerName)
        if (q.handler) params.append('Handler', q.handler)
        if (q.signingStart) params.append('SigningDate', q.signingStart)
        if (q.status) params.append('ApprovalStatus', q.status)
        params.append('t', String(Date.now()))

        const url = `http://localhost:5000/api/ContractManagementControllers/CargoOwner?${params.toString()}`
        const res = await fetch(url)
        const text = await res.text()
        let json: any
        try { json = JSON.parse(text) } catch { json = {} }
        const container = json?.data || {}
        total.value = Number(container?.TotalCount || 0)
        totalPage.value = Number(container?.TotalPage || 0)
        rows.value = Array.isArray(container?.data) ? container.data : []
    } catch (e) { console.error(e); rows.value = []; total.value = 0; totalPage.value = 0 }
    finally { loading.value = false }
}

function search() { page.value = 1; fetchList() }
function reset() { Object.assign(q, { contractTitle: '', unitName: '', ownerName: '', handler: '', signingStart: '', signingEnd: '', status: '' }); fetchList() }
function goto(p: number) { if (p < 1 || p > totalPage.value) return; page.value = p; fetchList() }

function view(r: any) { router.push(`/UpdateCargoOwnerContracts?id=${encodeURIComponent(r.id)}`) }
async function approve(r: any) { if (!confirm('确认通过？')) return; try { /* todo: call approval API */ } catch (e) { console.error(e); alert('审批失败，请重试') } }
async function reject(r: any) { if (!confirm('确认拒绝？')) return; try { /* todo: call reject API */ } catch (e) { console.error(e); alert('拒绝失败，请重试') } }

onMounted(() => { fetchList() })
</script>

<style scoped>
.page {
    padding: 16px
}

.title {
    font-size: 18px;
    margin-bottom: 12px
}

.search {
    background: #f7f7f7;
    padding: 12px;
    border-radius: 6px;
    margin-bottom: 12px
}

.row {
    display: flex;
    gap: 8px;
    align-items: center
}

.tabs {
    margin-bottom: 8px
}

.tab {
    padding: 8px 12px;
    border: 1px solid #eee;
    background: #fff;
    margin-right: 8px;
    cursor: pointer
}

.tab.active {
    background: #f0f0f0;
    border-bottom: 2px solid #1677ff
}

.table {
    width: 100%;
    border-collapse: collapse
}

.table th,
.table td {
    border: 1px solid #eee;
    padding: 8px
}

.pagination {
    margin-top: 12px;
    display: flex;
    gap: 12px;
    align-items: center
}

.num {
    min-width: 32px;
    height: 28px;
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    cursor: pointer
}

.num.active {
    background: #13c2c2;
    color: #fff;
    border-color: #13c2c2
}

.nav {
    min-width: 32px;
    height: 28px;
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    cursor: pointer
}

.sum {
    color: #666;
    margin-right: 6px
}

.jump {
    color: #666
}

.jump-input {
    width: 56px;
    height: 28px;
    padding: 0 6px;
    border: 1px solid #ddd;
    border-radius: 4px
}
</style>
